using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using CrystalDecisions.Shared;
using CrystalDecisions.CrystalReports.Engine;


public sealed class ReportHelper {

    public static TableLogOnInfos ConfigureCrystalReportLogonInfo( ReportDocument _reportDocument, string connStr ) {

        ConnectionInfo cnni = new ConnectionInfo();

        string str = GetConnectionStringElements( connStr, "Integrated Security" );
        if (str == "" || str.ToLower() == "false") {
            cnni.IntegratedSecurity = false;
        }
        else
            cnni.IntegratedSecurity = true;

        cnni.UserID = Convert.ToString( GetConnectionStringElements( connStr, "User ID" ) );
        cnni.Password = Convert.ToString( GetConnectionStringElements( connStr, "Password" ) );
        cnni.ServerName = GetConnectionStringElements( connStr, "Data Source" );
        cnni.DatabaseName = GetConnectionStringElements( connStr, "Initial Catalog" );

        CrystalDecisions.CrystalReports.Engine.Tables ts;

        ts = _reportDocument.Database.Tables;

        TableLogOnInfo li = new TableLogOnInfo();

        foreach (CrystalDecisions.CrystalReports.Engine.Table t in ts) {
            li = t.LogOnInfo;
            li.ConnectionInfo = cnni;
            t.ApplyLogOnInfo( li );
        }

        for (int i = 0; i < _reportDocument.Subreports.Count; i++) {
            CrystalDecisions.CrystalReports.Engine.Tables tbs;

            tbs = _reportDocument.Subreports[i].Database.Tables;

            TableLogOnInfo loi = new TableLogOnInfo();

            foreach (CrystalDecisions.CrystalReports.Engine.Table tb in tbs) {
                loi = tb.LogOnInfo;
                loi.ConnectionInfo = cnni;
                tb.ApplyLogOnInfo( loi );
            }
        }

        li.ConnectionInfo = cnni;

        TableLogOnInfos lis = new TableLogOnInfos();
        lis.Add( li );
        return lis;
    }

    private static string GetConnectionStringElements( string connStr, string valueStr ) {

        int index = connStr.ToLower().IndexOf( valueStr.ToLower() );
        if (index > -1) {
            string str = connStr.Substring( index + valueStr.Length + 1, connStr.Length - (index + valueStr.Length + 1) );
            index = str.IndexOf( ';' );
            if (index > -1) str = str.Substring( 0, index );
            return str;
        }
        else {
            return "";
        }
    }

}
